package com.yunhe.webmvc.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author LeiPeifeng
 * @version V1.0
 * @date 2017/10/31 0031 13:12
 * @Description: 文件的下载
 */
@WebServlet(name="download",urlPatterns = "/downimg")
public class DownServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding ( "utf-8" );
        String path = req.getParameter ( "path" );
        if (null != path && !path.isEmpty ()){
            File file = new File ( "/var/fs/"+path );
            if (file.exists ()){
                FileInputStream fileInputStream = new FileInputStream ( file );//从硬盘中读取
                ServletOutputStream outputStream = resp.getOutputStream ();//获得输出流
                byte[] bytes=new byte[1024*1024];
                int len;
                if ((len=fileInputStream.read (bytes))!=-1){
                    outputStream.write ( bytes,0,len );
                }
                outputStream.flush ();
                outputStream.close ();
            }
        }
    }
}
